package com.hy.utils;
/*
 * @ Date: 2024/5/14 9:40
 * @ Description: jwt工具
 **/

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class JwtUtils {
    private static  final String SECRET = "Carsales";//密钥
    private static  final Integer EXPIRATION = 1;//过期时间


    /* @Description: 生成Token
    * @Date: 2024/5/14 10:03
    * @paramType: String
    * @Param: name 用户名
    * @Return: String token
    */

    public String createJwt(String name) {
        Map<String, Object> header = new HashMap<>();
        String token = JWT.create()
                .withHeader(header)
                .withClaim("username", name)
                .withExpiresAt(generateExpirationDate())
                .sign(Algorithm.HMAC512(SECRET));
        return token;
    }

    /* @Description: 验证token是否有效
    * @Date: 2024/5/14 10:15
    * @paramType: String，String
    * @Param: token，username
    * @Return:
    */
    public boolean validateToken(String token,String username){
        String name = getUserNameFromToken(token);
        return username.equals(name) && !isTokenExpired(token);
    }

    /* @Description: 从token中获取用户名
    * @Date: 2024/5/14 10:13
    * @paramType:
    * @Param:
    * @Return:
    */
    public String getUserNameFromToken(String token){
        String username = getToken(token).getClaim("username").asString();
        return username;
    }

    /**
     * 判断token是否有效
     *
     * @param token
     * @return
     */
    private boolean isTokenExpired(String token) {
        Date expiresDate = getExpiredDateFromToken(token);
        return expiresDate.before(new Date());
    }

    /**
     * 判断token是否可以被刷新
     *
     * @param token
     * @return
     */
    public boolean canRefresh(String token) {
        return !isTokenExpired(token);
    }

    /**
     * 刷新token
     *
     * @param token
     * @return
     */
    public String refreshToken(String token) {
        return createJwt(getUserNameFromToken(token));
    }

    /* @Description: 从token中获取失效时间
    * @Date: 2024/5/14 10:17
    * @paramType: 
    * @Param: 
    * @Return: 
    */
    private Date getExpiredDateFromToken(String token) {
        return getToken(token).getExpiresAt();
    }

    /* @Description: 解析token
    * @Date: 2024/5/14 10:06
    * @paramType: String
    * @Param: token
    * @Return: DecodedJWT
    */
    private static DecodedJWT getToken(String token){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC512(SECRET))
                .build()
                .verify(token);
        return decodedJWT;
    }

    /**
     * 生成token失效时间
     *
     * @return
     */
    private Date generateExpirationDate() {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MARCH, EXPIRATION * 60);
        return instance.getTime();
    }

}
